import {Component, Input, OnInit, ViewChild} from '@angular/core';
import * as moment from "moment";
import {FetchService} from "../../../../core/net/fetch.service";
import * as _ from "lodash";
import {MenuItemModel} from "../../../../core/auth/auth.service";
import {NzTreeComponent} from "ng-zorro-antd";
import {endOfMonth, format, startOfMonth} from "date-fns";

@Component({
  selector: 'app-ecologic-water-multi',
  templateUrl: './ecologic-water-multi.component.html',
  styleUrls: ['./ecologic-water-multi.component.scss', '../ecologic-water.component.scss']
})
export class EcologicWaterMultiComponent implements OnInit {
  // tslint:disable-next-line:variable-name
  _dateRangeVal = [startOfMonth(new Date()), endOfMonth(new Date())];
  @Input()
  get dateRangeVal() {
    return this._dateRangeVal;
  }

  set dateRangeVal(val) {
    this._dateRangeVal = val;
    this.queryInfo();
  }

  treeData;
  checkedKeys;
  expandKeys;
  frId = '';
  lwId = '';

  chart1Opt;
  chart1OptChange;

  chart2Opt = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      },
      formatter: params => {
        const tar = params[0];
        return tar.name + '<br/>' + tar.seriesName + ' : ' + tar.value;
      }
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      splitLine: {show: false},
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: []
  };
  chart2OptChange;

  tableData = [];
  tableHeaders = [];
  pageNum = 1;
  pageSize = 10;

  @ViewChild('treeComponent') treeComponent: NzTreeComponent;

  constructor(private fetchService: FetchService) {
  }

  ngOnInit(): void {
    this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {apicode: 21}).subscribe(res => {
      const treeList = [...[{id: "0", pid: null, name: 'root'}], ...res];
      this.treeData = this.formatToCascadeData(treeList, "0");
      this.getTreeData(this.treeData);
      this.treeData = this.treeData[0].children;
      this.expandKeys = [this.treeData[0].key];
      this.checkedKeys = [this.treeData[0].children[0].key];
      setTimeout(() => {
        this.treeSelectChanged();
      }, 0);
    });
  }

  treeSelectChanged(): void {
    const selectedNodes = this.treeComponent.getCheckedNodeList();
    const frIdList = [];
    const lwIdList = [];
    selectedNodes.map(treeNode => {
      if (treeNode.origin.level == 1) {
        if (!frIdList.includes(treeNode.origin.id)) {
          frIdList.push(treeNode.origin.id);
        }
        treeNode.origin.children.map(child => {
          lwIdList.push(child.id);
        });
      } else {
        if (!frIdList.includes(treeNode.origin.pid)) {
          frIdList.push(treeNode.origin.pid);
        }
        lwIdList.push(treeNode.origin.id);
      }
    });
    this.frId = frIdList.map(item => item.replace(/m/, '')).join(',');
    this.lwId = lwIdList.join(',');
    this.queryInfo();
  }

  queryInfo(): void {
    if (this.frId) {
      const url = 'report/ecology/mutipleDataListByDate';
      const params = {
        frId: this.frId,
        lwId: this.lwId,
        stDate: format(this.dateRangeVal[0], 'YYYY-MM-DD'),
        edDate: format(this.dateRangeVal[1], 'YYYY-MM-DD')
      };
      console.log(params);
      this.fetchService.post<any>(url, params).subscribe(res => {
        this.getChart1Data(res);
        this.getChart2Data(res);
        this.getTableData(res);
      });
    }
  }

  getChart1Data(res) {
    const typeMap = {'1': '当日', '2': '累计'};
    const legendData = [];
    const seriesData = [];
    res.dataList.map(item => {
      legendData.push(item.name + typeMap[item.type]);
      seriesData.push({
        name: item.name + typeMap[item.type],
        type: 'line',
        smooth: true,
        yAxisIndex: item.type == '1' ? 0 : 1,
        data: item.valList
      });
    });
    this.chart1Opt = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          animation: false,
          label: {
            backgroundColor: "#505765"
          }
        }
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      legend: {
        data: legendData,
        bottom: 0
      },
      xAxis: {
        type: "category",
        data: res.dateRange
      },
      yAxis: [
        {
          name: "当日补水量(m³)",
          type: "value"
        },
        {
          name: "累计补水量(m³)",
          type: "value"
        }
      ],
      series: seriesData
    };
    this.chart1Opt = {...{}, ...this.chart1Opt};
  }

  getChart2Data(res) {
    const chart2Data = res.dataList.filter(list => list.type == 1);
    const xAxis = [];
    const seriesData = [];
    this.tableHeaders = [];
    chart2Data.map(item => {
      xAxis.push(item.name);
      seriesData.push(this.sum(item.valList).toFixed(2));
    });
    this.chart2OptChange = {
      xAxis: {
        data: xAxis
      },
      series: [
        {
          name: '补水量',
          type: 'bar',
          label: {
            fontSize: 18,
            show: true,
            position: 'inside'
          },
          itemStyle: {
            normal: {
              // 随机显示
              // color:function(d){return "#"+Math.floor(Math.random()*(256*256*256-1)).toString(16);}

              // 定制显示（按顺序）
              color: params => {
                const colorList = ['#C33531', '#EFE42A', '#64BD3D', '#EE9201', '#29AAE3', '#B74AE5', '#0AAF9F', '#E89589', '#16A085', '#4A235A', '#C39BD3 ', '#F9E79F', '#BA4A00', '#ECF0F1', '#616A6B', '#EAF2F8', '#4A235A', '#3498DB'];
                return colorList[params.dataIndex];
              }
            },
          },
          data: seriesData
        }
      ]
    };
  }

  getTableData(res): void {
    this.tableData = [];
    const chart2Data = res.dataList.filter(list => list.type == 1);
    chart2Data.map(item => {
      this.tableHeaders.push(item.name);
    });
    const rowHeaders = [...res.dateRange, '累计'];
    rowHeaders.map((dataItem, i) => {
      const tableObj: any = {total: 0};
      chart2Data.map((item, j) => {

        if (dataItem == '累计') {
          tableObj['time'] = dataItem;
          tableObj[item.name] = this.sum(item.valList);
          tableObj.total = tableObj.total + tableObj[item.name];
        } else {
          tableObj['time'] = dataItem;
          tableObj[item.name] = item.valList[i];
          tableObj.total += item.valList[i];
        }
        tableObj.total = parseFloat(tableObj.total.toFixed(2));
      });
      this.tableData.push(tableObj);
    });
  }

  private formatToCascadeData(data, rootId): any {
    const formatArr = [];
    for (const item of data) {
      const obj = {
        id: item.id,
        name: item.name,
        pid: item.pid,
        children: []
      };
      formatArr.push(obj);
    }
    if (formatArr.length > 1) {
      return this.listToTreeWithLevel(formatArr, null, 0, rootId);
    } else {
      formatArr[0].level = 1;
      return formatArr;
    }
  }

  private listToTreeWithLevel(list, parent, level, rootId?): Array<any> {
    const out = [];
    for (const node of list) {
      if (node.pid === parent) {
        node.level = level;
        const children = this.listToTreeWithLevel(list, node.id, level + 1, rootId);
        if (children.length) {
          node.children = children;
        }
        out.push(node);
      }
    }
    return out;
  }

  getTreeData(data) {
    data.map(item => {
      item.title = item.name;
      item.key = item.id;
      if (item.children && item.children.length) {
        this.getTreeData(item.children);
      } else {
        item.isLeaf = true;
      }
    });
  }

  sum(arr) {
    let s = 0;
    for (let i = 0; i < arr.length - 1; i++) {
      arr[i] = null ? 0 : arr[i];
      s += arr[i];
    }
    return s;
  }
}
